﻿// See https://aka.ms/new-console-template for more information
using ClosedXML.Excel;
using System.Text;


string excelFilePath = "11.xlsx";

// Load Excel file using ClosedXML
using (var workbook = new XLWorkbook(AppContext.BaseDirectory + "/" + excelFilePath))
{
    // Get the first worksheet
    var worksheet = workbook.Worksheets.Worksheet(1);

    // Convert Excel worksheet to HTML
    string htmlTable = ConvertWorksheetToHtmlTable(worksheet);

    // Print or use the HTML table as needed
    Console.WriteLine(htmlTable);
}


static string ConvertWorksheetToHtmlTable(IXLWorksheet worksheet)
{
    StringBuilder htmlBuilder = new StringBuilder();
    htmlBuilder.AppendLine("<table>");

    // Loop through rows
    for (int row = 1; row <= worksheet.RowsUsed().Count(); row++)
    {
        htmlBuilder.AppendLine("<tr>");

        // Loop through columns
        for (int col = 1; col <= worksheet.ColumnsUsed().Count(); col++)
        {
            IXLCell cell = worksheet.Cell(row, col);

            // Check if the cell is part of a merged range
            if (cell.MergedRange() != null)
            {
                // Skip cells within the merged range
                col += cell.MergedRange().ColumnCount() - 1;
            }

            // Append cell as HTML table cell
            htmlBuilder.Append("<td");
            if (cell.MergedRange() != null)
            {
                // Set rowspan and colspan attributes if necessary
                htmlBuilder.Append($" rowspan='{cell.MergedRange().RowCount()}'");
                htmlBuilder.Append($" colspan='{cell.MergedRange().ColumnCount()}'");
            }
            htmlBuilder.Append($">{cell.Value}</td>");
        }

        htmlBuilder.AppendLine("</tr>");
    }

    htmlBuilder.AppendLine("</table>");

    return htmlBuilder.ToString();
}